package site.icesky.springboot.rocketmq.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @ClassName: SpringContextUtil <br>
 * @Description: 获取bean的公共方法 <br>
 * @Package: site.icesky.springboot.rocketmq.util <br>
 * @author: suitianmou <br>
 * @Date: 2020/5/23-23:37 <br>
 * @version: 1.0 <br>
 * @see <br>
 * @since (从产品的哪一个版本此类被添加进来 ( 可选))<br>
 * 修改历史: <br>
 * 修改时间             修改人           版本变更           修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Component
public class SpringContextUtil implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        SpringContextUtil.beanFactory = beanFactory;
    }

    public static Object getBean(String name){
        return beanFactory.getBean(name);
    }

    public static <T>  T getBean(Class<T> clazz){
        return beanFactory.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz){
        return beanFactory.getBean(name, clazz);
    }

    public static List<Object> getBeansWithAnnotatio(Class<? extends Annotation> annotationType){
        Map<String, Object> beansWithAnnotation = beanFactory.getBeansWithAnnotation(annotationType);
        return beansWithAnnotation.entrySet().stream().map(entry -> entry.getValue()).collect(Collectors.toList());
    }


}
